package org.miyuki4j.cfgtool.app;

import lombok.extern.slf4j.Slf4j;
import org.miyuki4j.cfgtool.CfgApp;
import org.miyuki4j.cfgtool.Commands;
import org.miyuki4j.cfgtool.RunModeEnum;
import org.miyuki4j.cfgtool.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/28/星期一 17:29
 * @Version 1.0
 */
@SpringBootApplication(scanBasePackages = "org.miyuki4j.cfgtool", proxyBeanMethods = false)
@AutoConfiguration
@EnableAsync
@EnableScheduling
@EnableConfigurationProperties
@Configuration
@Slf4j
public class WebCfgApp extends CfgApp implements CommandLineRunner {

    private ConfigurableApplicationContext context;

    @Override
    public RunModeEnum runMode() {
        return RunModeEnum.WEB;
    }

    @Override
    public void run() {
        context = SpringApplication.run(getClass(), args);
        final Environment env = context.getEnvironment();
        final String port = env.getProperty("server.port");
        String contextPath = env.getProperty("server.servlet.context-path");
        if (contextPath == null){
            contextPath = "";
        } else if (StringUtils.isNotBlank(contextPath)){
            contextPath = contextPath.startsWith("/") ? contextPath : "/" + contextPath;
        }
        log.info("started, open in browser: http://localhost:{}{}/index", port, contextPath);
        log.debug("✅ {} running", getClass().getName());
    }

    @Override
    public void exit() {
        if (context != null && context.isActive()) {
            context.close();
        }
        super.exit();
    }

    @Override
    public void run(String... args) {
        String argStr = String.join(" ", args);
        try {
            log.debug("开始执行, args:{}", argStr);
            Commands.run(args);
        } catch (Exception e) {
            log.error("执行失败，args:{}", argStr, e);
        }
    }
}
